package com.how2java.tmall.service;

import com.how2java.tmall.dao.PropertyValueDao;
import com.how2java.tmall.pojo.Product;
import com.how2java.tmall.pojo.Property;
import com.how2java.tmall.pojo.PropertyValue;
import com.how2java.tmall.util.SpringContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@CacheConfig(cacheNames = "propertyValues")
public class PropertyValueService {

    @Autowired
    PropertyValueDao propertyValueDao;

    @Autowired
    PropertyService propertyService;

    @CacheEvict(allEntries = true)
    public void update(PropertyValue bean){
        propertyValueDao.save(bean);
    }

    public void init(Product product){
        PropertyValueService propertyValueService = SpringContextUtil.getBean(PropertyValueService.class);
        List<Property> propertyList = propertyService.listByCategory(product.getCategory());
        for(Property property : propertyList){
            PropertyValue propertyValue = propertyValueService.getByPropertyAndProduct(property,product);
            if(null == propertyValue){
                propertyValue = new PropertyValue();
                propertyValue.setProduct(product);
                propertyValue.setProperty(property);
                propertyValueService.add(propertyValue);
            }
        }
    }

    @CacheEvict(allEntries = true)
    public void add(PropertyValue bean){
        propertyValueDao.save(bean);
    }

    @Cacheable(key = "'properties-ptid-'+#p0.id+'-pid-'+#p1.id")
    public PropertyValue getByPropertyAndProduct(Property property,Product product){
        return propertyValueDao.getByPropertyAndProduct(property,product);
    }



    @Cacheable(key="'propertyValues-pid-'+#p0.id")
    public List<PropertyValue> list(Product product){

        return propertyValueDao.findByProductOrderByIdDesc(product);
    }



}
